<template>
  <div class="search-suggestion">
    <van-cell
      icon="search"
      v-for="(text, index) in suggestions"
      :key="index"
      @click="$emit('search', text)"
    >
      <div slot="title" v-html="highlight(text)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from '@/api/search.js'
import { debounce } from 'lodash'
export default {
  name: 'searchSuggest',
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      suggestions: [] // 联想的数据
    }
  },
  created () {},
  mounted () {},
  methods: {
    async loadSearchSuggestions (q) {
      try {
        const { data } = await getSearchSuggestions(q)
        this.suggestions = data.data.options
      } catch (err) {
        this.$toast('获取数据失败,请稍后重试')
      }
    },
    highlight (text) {
      const highlightStr = `<span style="color:blue">${this.searchText}</span>`
      const req = new RegExp(this.searchText, 'gi')
      return text.replace(req, highlightStr)
    }
  },
  watch: {
    searchText: {
      // 防抖 debounce 来自于lodash插件
      handler: debounce(function (value) {
        this.loadSearchSuggestions(value)
      }, 200),
      immediate: true // 该回调会在侦听后立即调用
    }
  }
}
</script>

<style scoped lang="less"></style>
